package com.tmp;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Base64;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class CallFieldMethod {
    public static void main(String[] args) {
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost("http://222.247.54.188:8090/fmd/fd/phis/queryList?start=0&limit=1");

            String sign="OXyrz0ZfCCCaMpC3DtpR4UgihVEjo0KU3bwV74/sxZCXkZDrq/HEyA9fFQA28avsYuFl/F4FUhGxMoyaZXuDmuVNqxfDXdQzQTMncJXc5CFbo+o9y7tqFh6Rq8CNCUQLunHn5+ZFqbiiwgRSSSGzAShJH01lVf/vIB9aQvzMlYg=";
            String token="175e6e55-911f-4ba2-b03f-6cfc40b68813";
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Accept-Encoding", "gzip, deflate");
            httpPost.setHeader("Sign", sign);
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            httpPost.setHeader("Token", token);


            // 设置请求体
            String jsonInputString = "61055049ea8f3948c6f2602a0d739901086f18f4c17781747a63aad8a8fd124f370f41e5a9eb4d30c6e2c7d276af822d4219b0cc0f9590c312ce05d5f7fcd8ed272c217d1cbbeee9e91a311a5fd19de3937e26e62b741d230dac75b06ac135f163815816f4c49c465f534029fbd94e306140ea0cd1095a6bcd1547082ecd258ea7f73257c8acde13daa36791732c44d6ffa08370be2b1656f06f5835169126ce8f7a05b0391df6685ede005f5bc41fa499624270696516917b0694478d133f56958c6c3d1ea10cb4ab864cbff4313f5b0652088fa387335dc66e999a0601940d506f243d4bfb0b1cc14366004bb7ca7cbe5416ea026e2618dfef80207ec657c4f1f2a2f8e0fdadb3e4b96292e51e0e73";
            StringEntity entity = new StringEntity(jsonInputString, "UTF-8");
            httpPost.setEntity(entity);


            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Code: " + statusCode);


                // 获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    // 自动解压响应内容
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    //需要进行gzip解压处理
//                    responseString = EntityUtils.toString(new GzipDecompressingEntity(responseEntity), "UTF-8");

                    // 打印响应内容
                    System.out.println("Response: " + responseString);
                    decompressDeflate(responseString);

                    // 将响应内容写入文件
                    /*try (FileWriter fileWriter = new FileWriter("response.txt")) {
                        fileWriter.write(responseString);
                    }*/
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Deflate 解压（处理不带 zlib 头的原始数据）
    public static String decompressDeflate(String compressedStr) throws IOException {
        if (compressedStr == null || compressedStr.isEmpty()) {
            throw new IllegalArgumentException("压缩字符串不能为空");
        }

        // 验证是否为合法的 Base64 编码
        if (!isBase64(compressedStr)) {
            throw new IllegalArgumentException("输入字符串不是合法的 Base64 编码");
        }

        // 清理输入字符串（去除多余字符）
        String cleanedStr = compressedStr.replaceAll("[^A-Za-z0-9+/=]", "");

        // 解码 Base64 字符串
        byte[] compressedData;
        try {
            compressedData = Base64.getDecoder().decode(cleanedStr);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Base64 解码失败，请检查输入字符串", e);
        }

        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
             InflaterInputStream iis = new InflaterInputStream(bis, new Inflater(true)); // 不带 zlib 头
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = iis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toString("UTF-8");
        }
    }

    // 检查字符串是否为合法的 Base64 编码
    private static boolean isBase64(String str) {
        Pattern pattern = Pattern.compile("^[A-Za-z0-9+/=]*$");
        return pattern.matcher(str).matches();
    }


}
